import {Component, ViewChild} from '@angular/core';
import {IonicPage, NavParams} from 'ionic-angular';
import {ChatListener, ChatProvider} from "@providers/interface/chat";
import {StorageProvider} from "@providers/storage";
import {Util} from "@providers/util";

/**
 * Generated class for the ChatPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-chat',
  templateUrl: 'chat.html',
})
export class ChatPage implements ChatListener {

  @ViewChild('content') content;

  room_id: string = '1';
  room_name: string = '1';
  person_id: string = this.storage.getUserInfo()['SessionID'];
  list: any[] = [];
  text: string = "";

  page_num: number = 1;

  constructor(private chat: ChatProvider,
              private storage: StorageProvider,
              private navParams: NavParams) {
    this.room_id = this.navParams.get("ROOM_ID");
    this.room_name = this.navParams.get("ROOM_NAME");
  }

  scrollToBottom() {
    setTimeout(() => {
      if (this.content.scrollToBottom) {
        this.content.scrollToBottom(0);
      }
    }, 200)
  }

  ionViewDidLoad() {
    this.chatHistory();
    this.chat.registerListener(this);
  }

  ionViewWillUnload() {
    this.chat.unregisterListener(this);
  }

  send() {
    this.chat.sendMessage(this.room_id, 'text', this.text);
    this.text = "";
  }

  onMessage(m) {
    this.list.push(m);
    if (this.content) this.scrollToBottom()
  }

  isMe(person_id): boolean {
    return person_id == this.person_id;
  }

  chatHistory(): Promise<any> {
    return new Promise((resolve) => {
      this.chat.chatHistory(this.room_id, 1, 99999)
        .then(v => {
          this.list = this.list || [];
          this.list = this.list.concat(v['history'] || []);
          this.scrollToBottom();
        }).then(v => resolve(v))
    })
  }

  refresh(refresher?: any) {
    this.chat.chatHistory(this.room_id, ++this.page_num, 10)
      .then(v => {
        let history = (v['history'] || []);
        this.list = this.list || [];
        [...this.list, ...history]
        // this.list = history.concat(this.list);

        if (Util.isNull(this.list)) {
          let _id = 'chat-0';
          let _index = document.getElementById(_id);
          _index.scrollIntoView();
        }
      }).then(v => {
      if (refresher) {
        setTimeout(() => {
          refresher.complete();
        }, 500);
      }
    });
  }

  setElement(item, event) {
    console.log(event)
  }
}
